'use strict';

const Service = require('egg').Service;
const utility = require("utility") //密码加密

class PostService extends Service {
  // 注册
  async postRegister(obj) {
    const { ctx } = this;
    let { email, qq, password1, password2, userName } = obj;
    let password;
    return new Promise(async (resolve, reject) => {
      if (password1 == password2) {
        password = await utility.md5(password1);
      } else {
        return resolve({ code: 201, msg: '注册密码不一致' });
      }
      if(!email.includes('@')) return resolve({ code: 201, msg: '注册手机号格式错误' });
      let FindArr = await ctx.model.Users.findOne({ email: email });
      if (FindArr) return resolve({ code: 201, msg: '用户以存在' });
      await ctx.model.Users.create({
        userName,
        password: password,
        email,
        qq
      }).then(data => {
        // console.log('data0', data)
        if (!data) return resolve({ code: 201, msg: '用户创建失败' });
        return resolve({ code: 200, msg: '用户创建成功' });
      }).catch(err => {
        console.log('err', err);
        return resolve({ code: 201, msg: '用户创建失败' });
      })
    })
  }

  // 登录
  async postLogin(obj) {
    const { ctx, app } = this;
    let { email, password } = obj;
    return new Promise(async (resolve, reject) => {
      let FindArr = await ctx.model.Users.findOne({ email: email });
      // console.log(FindArr);
      if (!FindArr) return resolve({ code: 201, msg: '用户不存在' });
      let pw = await utility.md5(password)
      if(pw != FindArr.password)  return resolve({ code: 201, msg: '密码错误' });

      let token = app.jwt.sign({email, password, role: FindArr.role}, app.config.jwt.secret, { expiresIn: "30 days"});      
      return  resolve({ code: 200, msg: '登录成功', data: {
        token
      } })
    });
  }

}

module.exports = PostService;
